<template>
  <div class="padding-l-20 padding-r-20 padding-t-20 h-100 table-page" id="table-page">
    <filter-bar>
      <div slot="left-bar">
        <a-space>
          <a-input allowClear class="_searchInput position-r" placeholder="报告编号" enter-button v-model="searchForm.reportNumber" />
          <a-input allowClear class="_searchInput position-r" placeholder="提交人姓名" enter-button v-model="searchForm.userName" />
          <a-input allowClear class="_searchInput position-r" placeholder="任务名称" enter-button v-model="searchForm.taskName" />
          <my-tree-select
            class="orgSelect"
            ref="myTree"
            :tree-data="orgTree"
            :value="treeValue"
            placeholder="请选择所属组织"
            :replaceFields="replaceFields"
            @selectChange="selectChange"
          />
          <a-select allowClear placeholder="请选择检测类型" style="width: 180px" v-model="searchForm.taskType">
            <a-select-option v-for="(item, index) in taskTypeMap" :key="index" :value="index">{{ item }} </a-select-option>
          </a-select>
          <a-range-picker valueFormat="YYYY-MM-DD" v-model="searchForm.searchTime" style="width: 250px">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
          <a-button
            class="nbcs-btn nbcs-btn-search"
            @click="
              page.page = 1;
              getList(page, searchForm);
            "
            >查询
          </a-button>
          <a-button class="nbcs-btn nbcs-btn-common" @click="initSearch">重置</a-button>
        </a-space>
      </div>
    </filter-bar>
    <interval-bg></interval-bg>
    <opt-bar>
      <div slot="left-bar">检测记录</div>
      <div slot="right-bar">
        <a-space>
          <a-button class="nbcs-btn nbcs-btn-default" @click="exportList" :loading="exportLoading"> 导出 </a-button>
        </a-space>
      </div>
    </opt-bar>
    <a-table bordered ref="_table" :columns="columns" :data-source="list" :pagination="pageConfig" rowKey="id" :loading="loading" :scroll="{ x: 1000, y: tableHeight }">
      <span slot="violationCount" slot-scope="text">{{ text ? text + '处' : '' }}</span>
      <span slot="taskType" slot-scope="text, record">
        {{ taskTypeMap[record.taskType] }}
      </span>
      <span slot="auditStatus" slot-scope="text, record">
        <a-tag v-if="record.auditStatus == 1" class="tag-green">
          检测完成
        </a-tag>
        <a-progress v-else-if="record.auditStatus == 0" :percent="record.auditProcess" />
        <a-tag v-else class="tag-red" @click="checkError('失败原因', record.errorMsg)">
          检测失败
        </a-tag>
      </span>
      <span slot="action" class="operation" slot-scope="text, record">
        <!-- <a-space size="middle"> -->
          <a v-if="record.auditStatus != 0 && record.taskType != 'word' && record.taskType != 'pdf'" @click="detail(record.id, record.taskType)">查看检测结果</a>
          <a v-if="record.auditStatus != 0 && (record.taskType == 'word' || record.taskType == 'pdf')" @click="exportDocData(record.taskAllId, record.fileType)">下载标注文档</a>

          <template v-if="record.auditStatus != 0 && (record.taskType == 'image' || record.taskType == 'audio'|| record.taskType == 'video')">
            <a-divider type="vertical"  />
            <a @click="detailExport(record.id, record.taskType)" :loading="exportDetailLoading">导出检测结果</a>
          </template>
          <a-divider type="vertical" v-if="record.auditStatus != 0" />
          <a v-if="record.auditStatus != 0" @click="logExport(record.id, record.taskType)">下载检测报告</a>
          <a-divider type="vertical" v-if="record.auditStatus != 0" />
          <a-popconfirm title="确定删除吗？" @confirm="del(record)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a class="table-red-btn">删除</a>
          </a-popconfirm>
        <!-- </a-space> -->
      </span>
    </a-table>
    <result-detail ref="resultDetail"></result-detail>
  </div>
</template>

<script>
import { recordList, delRecord, exportRecordList, exportRecord } from '@/services/verify';
import FilterBar from '@/layouts/FilterBar';
import {docExport, exportDetail} from '../../services/verify';
import OptBar from '@/layouts/OptBar';
import IntervalBg from '@/layouts/IntervalBg';
import myTreeSelect from '../components/myTreeSelect';
import { list2Tree } from '@/utils/common';
import { getOrgByUser } from '@/services/org';
import { exportExcel, blobToJson } from '@/utils/util';
import ResultDetail from './components/ResultDetail.vue';
import { getContentCompany } from '@/utils/verifyUtil';
import { checkError } from '@/utils/myAnt';
import {getCheckElapsedTime} from "../../utils/util";

export default {
  name: 'VerifyRecordList',
  components: { myTreeSelect, OptBar, IntervalBg, FilterBar, ResultDetail },
  data() {
    return {
      taskTypeMap: {
        text: '文本',
        image: '图片',
        video: '视频',
        audio: '音频',
        ppt: 'PPT',
        word: 'WORD',
        pdf: 'PDF'
      },
      orgTree: [],
      treeValue: undefined,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id'
      },
      tableHeight: 0,
      loading: false,
      exportLoading: false,
      exportDetailLoading: false,
      searchForm: {
        reportNumber: '',
        userName: '',
        taskName: '',
        taskType: undefined,
        searchTime: [],
        orgId: ''
      },
      list: [],
      columns: [
        {
          title: '任务名称',
          dataIndex: 'taskName',
          width: 250
        },
        {
          title: '报告编号',
          dataIndex: 'reportNumber',
          width: 180
        },
        {
          title: '内容长度',
          dataIndex: 'textCount',
          width: 120,
          customRender: (text, record) => {
            let count = text;
            if (record.taskType == 'video' || record.taskType == 'audio') {
              count = record.vaLength;
            }

            return count + getContentCompany(record.taskType);
          }
        },
        {
          title: '检测类型',
          dataIndex: 'taskType',
          scopedSlots: { customRender: 'taskType' },
          width: 100
        },
        { title: '违规风险数', dataIndex: 'violationCount', width: 120, scopedSlots: { customRender: 'violationCount' } },
        {
          title: '送审时间',
          dataIndex: 'createTime',
          width: 180
        },
        {
          title: '完成时间',
          dataIndex: 'auditTime',
          width: 180
        },
        {
          title: '检测耗时',
          dataIndex: 'elapsedTime',
          width: 180,
          align: 'center'
        },
        {
          width: 120,
          title: '检测状态',
          dataIndex: 'auditStatus',
          scopedSlots: { customRender: 'auditStatus' },
          align: 'center'
        },
        {
          title: '提交人',
          dataIndex: 'userName',
          width: 120
        },
        {
          title: '所属部门',
          dataIndex: 'organName',
          width: 150
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 280,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      pageConfig: {
        showQuickJumper: true,
        hideOnSinglePage: false, //只有一页时是否隐藏分页器
        showSizeChanger: true,
        defaultPageSize: 20,
        pageSizeOptions: ['20', '30', '50'],
        total: 0,
        current: 1,
        showTotal: total => {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (page, pageSize) => {
          this.page.page = 1;
          this.page.pageSize = pageSize;
          this.getList(this.page, this.searchForm);
        },
        onChange: page => {
          this.page.page = page;
          this.pageConfig.current = page;
          this.getList(this.page, this.searchForm);
        }
      },
      page: {
        page: 1,
        pageSize: 20
      }
    };
  },
  computed: {},
  created() {
    this.getList(this.page, this.searchForm);
    this.getOrgAll();
  },
  mounted() {
    this.tableHeight = document.querySelector('.table-page').clientHeight - 276;
  },
  methods: {
    checkError,
    del(obj) {
      delRecord({ id: obj.id }).then(res => {
        if (res.data.code === 0) {
          this.$message.success('删除成功');
          this.getList(this.page, this.searchForm);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    initSearch() {
      this.searchForm = {
        taskName: '',
        taskType: undefined,
        searchTime: [],
        orgId: ''
      };
      this.treeValue = undefined;
    },
    getOrgAll() {
      getOrgByUser({ isFilterSys: 1 }).then(res => {
        if (res.data.code === 0) {
          this.orgTree = list2Tree(res.data.data);
        }
      });
    },
    selectChange(value) {
      this.searchForm.orgId = value;
      this.treeValue = value;
      //   this.page.page = 1;
      //   this.getList(this.page, this.searchForm);
    },
    getList(page, params) {
      let searchForm = {
        ...params,
        reportNumber: params.reportNumber != null ? params.reportNumber.trim() : params.reportNumber,
        userName: params.userName != null ? params.userName.trim() : params.userName
      };
      searchForm.searchTime = undefined;
      this.loading = true;
      if (this.searchForm.searchTime[0]) {
        searchForm.beginTime = this.searchForm.searchTime[0] + ' 00:00:00';
      }
      if (this.searchForm.searchTime[1]) {
        searchForm.endTime = this.searchForm.searchTime[1] + ' 23:59:59';
      }
      let queryParam = Object.assign(
        {
          page: page.page,
          pageSize: page.pageSize
        },
        searchForm
      );
      recordList(queryParam).then(res => {
        this.loading = false;
        const { data } = res.data;
        this.list = data.list;
        // 检测耗时
        data.list.forEach(item => {
          //计算耗时
          item.elapsedTime = getCheckElapsedTime(item.createTime, item.auditTime)
        });
        this.pageConfig.current = data.page;
        this.pageConfig.total = data.totalRow;
      });
    },
    async exportList() {
      this.exportLoading = true;
      let searchForm = { ...this.searchForm };
      searchForm.searchTime = undefined;
      if (this.searchForm.searchTime[0]) {
        searchForm.beginTime = this.searchForm.searchTime[0] + ' 00:00:00';
      }
      if (this.searchForm.searchTime[1]) {
        searchForm.endTime = this.searchForm.searchTime[1] + ' 23:59:59';
      }
      let res = await exportRecordList(searchForm);
      console.log(res);
      exportExcel(res.data, '检测记录.xlsx');
      this.exportLoading = false;
    },
    detail(id, taskType) {
      this.$refs.resultDetail.changeForm(true, { id, taskType });
    },
    async logExport(id) {
      this.exportLoading = true;
      let res = await exportRecord({ id });
      this.exportLoading = false;
      if (res.data.type == 'application/json') {
        blobToJson(res.data).then(res => {
          if (res.code == 401) {
            this.$message.warning('登录已失效，请重新登录');
            this.$router.replace({ path: '/login' });
          } else {
            this.$message.error(res.message);
          }
        });
      } else {
        exportExcel(res.data, '检测报告.pdf');
      }
    },
    exportDocData(taskAllId, fileType) {
      this.exportLoading = true;
      docExport(
        Object.assign({
          taskAllId: taskAllId
        })
      ).then(res => {
        this.exportLoading = false;
        console.log(res);
        if (res.status === 200) {
          exportExcel(res.data, '文档检测.' + fileType);
        } else {
          this.$message.error('当前任务没有生成标注文档');
        }
      });
    },
    async detailExport(id) {
      this.exportDetailLoading = true;
      let res = await exportDetail({ id });
      this.exportDetailLoading = false;
      if (res.data.type == 'application/json') {
        blobToJson(res.data).then(res => {
          if (res.code == 401) {
            this.$message.warning('登录已失效，请重新登录');
            this.$router.replace({ path: '/login' });
          } else {
            this.$message.error(res.message);
          }
        });
      } else {
        exportExcel(res.data, '检测结果.pdf');
      }
    }
  }
};
</script>

<style lang="less" scoped>
.select {
  width: 170px;

  /deep/ .ant-select-selection {
    width: 100%;
  }
}

._input {
  width: 180px;
}

.table-page {
  .ant-table-wrapper {
    max-height: calc(100% - 150px);
  }
}

.orgSelect {
  width: 170px;
}

.operation{
  a {
    white-space: nowrap;
  }
}
</style>
